import Taro, { Component } from '@tarojs/taro'
import { View, Picker } from '@tarojs/components'
import { AtForm, AtInput, AtIcon, AtTextarea, AtSwitch, AtButton } from 'taro-ui'
import { Header } from '../common/header';

import '../common/header.scss'
import './add.scss'
import '../../icon.scss'

export default class Add extends Component {

  constructor(){
    super();
    this.state = {
      name:'',
      mobile:'',
      useing:false,
      address:'',
      selector: [],
      province: [],
      city: [],
      district: [],
      selectProvince:null,
      selectCity:null,
      selectDistrict:null,
      loading:false,
      back:1,
      id:null,
    }
  }

  componentWillMount () {}

  componentDidMount () {
    let that = this;
    let user = Taro.getStorageSync('user');

    let id = parseInt(this.$router.params.id)?parseInt(this.$router.params.id):null;
    that.setState({
      back:parseInt(this.$router.params.back),
      id:id
    });
    if(id){
      Taro.request({
        credentials:'include',
        url: 'https://guoxiaojian.guoxiaoge.cn/api/user/address/info/'+id,
        data:{
          token : user.token
        },
        success:(res) => {
          if(res.statusCode === 200){
            if(res.data.status === 'SUCCESS'){
                that.setState({
                  name:res.data.data.name,
                  mobile:res.data.data.mobile,
                  useing:res.data.data.useing,
                  address:res.data.data.address,
                  selectProvince:{
                    id:res.data.data.province_id,
                    name:res.data.data.province
                  },
                  selectCity:{
                    id:res.data.data.city_id,
                    name:res.data.data.city
                  },
                  selectDistrict:{
                    id:res.data.data.district_id,
                    name:res.data.data.district
                  },
                });
            }else{
              if(res.data.status === 'FAILED'){
                if(res.data.failedCode === 'NO_LOGIN'){
                  Taro.navigateTo({
                    url:'/pages/login/login'
                  });
                }
              }
            }
          }
        }
      })
    }
    Taro.request({
      credentials:'include',
      url: 'https://guoxiaojian.guoxiaoge.cn/api/tool/district/init',
      data:{
        token : user.token
      },
      success:(res) => {
        if(res.statusCode === 200){
          if(res.data.status === 'SUCCESS'){
              let selectorP = [];
              let selectorC = [];
              let selectorD = [];
              let selector = [];

              let province = res.data.data.province;
              let city = res.data.data.city;
              let district = res.data.data.district;
              for(let i = 0; i<province.length; i++){
                selectorP.push(province[i].name);
              }
              selector.push(selectorP);
              for(let i = 0; i<city.length; i++){
                selectorC.push(city[i].name);
              }
              selector.push(selectorC);
              for(let i = 0; i<district.length; i++){
                selectorD.push(district[i].name);
              }
              selector.push(selectorD);

              that.setState({
                province: province,
                city: city,
                district: district,
                selector: selector
              });

          }else{
            if(res.data.status === 'FAILED'){
              if(res.data.failedCode === 'NO_LOGIN'){
                Taro.navigateTo({
                  url:'/pages/login/login'
                });
              }
            }
          }
        }
      }
    })
  }

  componentWillUnmount () { }

  componentDidShow () { }

  componentDidHide () { }

  onClickLeftIcon(){
    Taro.navigateTo({
      url:'/pages/index/index'
    });
  }

  handleChange(field, value){
    if(field === 'name'){
      this.setState({
        name:value,
      })
    }
    if(field === 'mobile'){
      this.setState({
        mobile:value,
      })
    }
    if(field === 'address'){
      this.setState({
        address:value.detail.value,
      })
    }

    if(field === 'useing'){
      this.setState({
        useing:!this.state.useing,
      })
    }
  }

  handleDistrictChange(e){
    let province = this.state.province[e.detail.value[0]?e.detail.value[0]:0]
    let city = this.state.city[e.detail.value[1]?e.detail.value[1]:0]
    let district = this.state.district[e.detail.value[2]?e.detail.value[2]:0]
    this.setState({
      selectProvince:province,
      selectCity:city,
      selectDistrict:district,
    });
  }

  onColumnchange(e){
    let that = this;
    let user = Taro.getStorageSync('user');

    let parent_id = 0;
    let level = 'province';
    if(e.detail.column === 0){
      parent_id = this.state.province[e.detail.value].id;
      level = 'city';
    }
    if(e.detail.column === 1){
      parent_id = this.state.city[e.detail.value].id;
      level = 'district';
    }
    if(parent_id > 0){
      Taro.request({
        credentials:'include',
        url: 'https://guoxiaojian.guoxiaoge.cn/api/tool/district',
        data:{
          parent_id: parent_id,
          token : user.token,
          level: level
        },
        success:(res) => {
          if(res.statusCode === 200){
            if(res.data.status === 'SUCCESS'){
                let selectorC = [];
                let selectorD = [];
                let selector = this.state.selector;
                for(let i = 0; i<res.data.data.city.length; i++){
                  selectorC.push(res.data.data.city[i].name);
                }
                for(let i = 0; i<res.data.data.district.length; i++){
                  selectorD.push(res.data.data.district[i].name);
                }
                if(e.detail.column == 0){
                  selector[1] = selectorC;
                  selector[2] = selectorD;
                  that.setState({
                    city: res.data.data.city,
                    district: res.data.data.district,
                    selector: selector
                  });
                }else{
                  selector[2] = selectorD;
                  that.setState({
                    district: res.data.data.district,
                    selector: selector
                  });
                }
            }else{
              if(res.data.status === 'FAILED'){
                if(res.data.failedCode === 'NO_LOGIN'){
                  Taro.navigateTo({
                    url:'/pages/login/login'
                  });
                }
              }
            }
          }
        }
      })
    }
  }


  handleSubmit(){
    let that = this;
    let user = Taro.getStorageSync('user');

    that.setState({
      loading:true
    });
    Taro.request({
      credentials:'include',
      url: 'https://guoxiaojian.guoxiaoge.cn/api/user/address/add',
      method:'POST',
      data:{
        name: that.state.name,
        mobile: that.state.mobile,
        useing:that.state.useing,
        city: that.state.selectCity.id,
        province: that.state.selectProvince.id,
        district: that.state.selectDistrict.id,
        address: that.state.address,
        token : user.token
      },
      success:(res) => {
        if(res.statusCode === 200){
          if(res.data.status === 'SUCCESS'){
            that.setState({
              loading:false
            });

            if(that.state.back === 1){
              Taro.navigateTo({
                url: '/pages/address/index'
              });
            }
          }else{
            if(res.data.status === 'FAILED'){
              if(res.data.failedCode === 'NO_LOGIN'){
                Taro.navigateTo({
                  url:'/pages/login/login'
                });
              }
            }
          }
        }
      }
    })
  }

  handleUpdateSubmit(){
    let that = this;
    let user = Taro.getStorageSync('user');

    that.setState({
      loading:true
    });
    Taro.request({
      credentials:'include',
      url: 'https://guoxiaojian.guoxiaoge.cn/api/user/address/update',
      method:'POST',
      data:{
        id:that.state.id,
        name: that.state.name,
        mobile: that.state.mobile,
        useing:that.state.useing,
        city: that.state.selectCity.id,
        province: that.state.selectProvince.id,
        district: that.state.selectDistrict.id,
        address: that.state.address,
        token : user.token
      },
      success:(res) => {
        if(res.statusCode === 200){
          if(res.data.status === 'SUCCESS'){
            that.setState({
              loading:false
            });

            if(that.state.back === 1){
              Taro.navigateTo({
                url: '/pages/address/index'
              });
            }
          }else{
            if(res.data.status === 'FAILED'){
              if(res.data.failedCode === 'NO_LOGIN'){
                Taro.navigateTo({
                  url:'/pages/login/login'
                });
              }
            }
          }
        }
      }
    })
  }

  render () {
    return (
      <View>
       <Header 
          leftIconType='chevron-left' 
          onClickLeftIcon={this.onClickLeftIcon} 
          title={this.state.id?'修改收货地址':'添加收货地址'}>
        </Header>
        <View>
          <AtForm>
            <AtInput
              name='name'
              title='收货人'
              type='text'
              border={false}
              placeholder='请输入收货人'
              value={this.state.name}
              onChange={this.handleChange.bind(this, 'name')}
            />
            <AtInput
              name='mobile'
              title='联系电话'
              type='phone'
              border={false}
              placeholder='请输入联系电话'
              value={this.state.mobile}
              onChange={this.handleChange.bind(this, 'mobile')}
            />
            <Picker mode='multiSelector' value={'0'} range={this.state.selector} onChange={this.handleDistrictChange} onColumnchange={this.onColumnchange}>
              <View className='picker-view'>
                <View className='picker-view-title'>配送地址</View>
                <View  className='picker-view-notice'>
                  <View>
                    {
                      this.state.selectProvince
                      ?
                      this.state.selectProvince.name
                      :
                      "请选择省"
                    }
                    {
                      this.state.selectCity
                      ?
                      this.state.selectCity.name
                      :"市"
                    }
                    {
                      this.state.selectDistrict
                      ?
                      this.state.selectDistrict.name
                      :"区"
                    }
                    </View>
                  <View>
                    <AtIcon value='chevron-right' size='22' color='#B1B1B1'></AtIcon>
                  </View>
                </View>
              </View>
            </Picker>
            <AtTextarea
              count={false}
              value={this.state.address}
              border={false}
              onChange={this.handleChange.bind(this, 'address')}
              maxlength='200'
              placeholder='请填写详细地址(街道、楼牌号等)'
            />
          </AtForm>
          <View className='line'></View>
          <AtForm>
            <AtSwitch title='设为默认' color="#F2CA26" checked={this.state.useing} onChange={this.handleChange.bind(this, 'useing')} />
          </AtForm>

          <View className='line h80'></View>
          <View className='address-submit'>
              {
                this.state.id
                ?
                <AtButton loading={this.state.loading} onClick={this.handleUpdateSubmit} type='primary'>修改</AtButton>
                :
                <AtButton loading={this.state.loading} onClick={this.handleSubmit} type='primary'>提交</AtButton>
              }
          </View>
        </View>
      </View>
    )
  }
}